package com.xzakota.minesweeper.widget.image;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 加载动画图像，待优化
 *
 * @author Xzakota
 */
public class LoadingImage extends JPanel implements ActionListener {
    private int angle = 0;
    private boolean isLooping = true;

    public LoadingImage(boolean loop) {
        this.isLooping = loop;

        Timer timer = new Timer(100, this);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        int size = 50;

        g2d.translate(centerX, centerY);
        g2d.rotate(Math.toRadians(angle));
        g2d.fillRect(-size / 2, -size / 2, size, size);
        g2d.rotate(-Math.toRadians(angle));
        g2d.translate(-centerX, -centerY);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        angle += 10;
        if (!isLooping && angle >= 360) {
            ((Timer) e.getSource()).stop();
        }
        repaint();
    }
}
